package com.cy.jt.security.config;

import com.cy.jt.security.config.handler.DefaultAccessDeniedExceptionHandler;
import com.cy.jt.security.config.handler.DefaultAuthenticationEntryPoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

//开启权限管理功能
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭跨域攻击
        http.csrf().disable();
        //自定义登录表单
        http.formLogin()
                .loginPage("/login.html")           //设置登录页面
                .loginProcessingUrl("/login")       //设置登录请求的处理地址form表单中的action
                //.usernameParameter("username")      //设置登录名 默认就为 name=username
                //.passwordParameter("password")      //设置密码   默认就为 name=password
                .defaultSuccessUrl("/index.html");    //设置登录成功跳转页面
                //.failureUrl("/login.html?error");   //设置登录失败跳转页面
                //.successHandler(new RedirectAuthenticationSuccessHandler())  //定义成功处理器
                //.failureHandler(new RedirectAuthenticationFailureHandler()); //定义失败处理器
        //设置登出
        http.logout().logoutUrl("/logout")
                    .logoutSuccessUrl("/login.html?logout");
        http.exceptionHandling()
                .authenticationEntryPoint(new DefaultAuthenticationEntryPoint())
                .accessDeniedHandler(new DefaultAccessDeniedExceptionHandler());
        //控制资源放行
        http.authorizeRequests()
                .antMatchers("/login.html",
                        "/images/*").permitAll()     //设置放行的资源
                .anyRequest().authenticated();      //设置需要认证的请求 所有请求
    }
}
